package Classic150;

import java.util.Stack;

public class 逆波兰表达式求值 {
    /*
        栈的典型应用，注意switch的用法 -> 与 : 的区别，优化：使用数组模拟栈
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            switch (token) {
                case "+" -> {
                    int x = stack.pop();
                    stack.push(stack.pop() + x);
                }
                case "-" -> {
                    int x = stack.pop();
                    stack.push(stack.pop() - x);
                }
                case "*" -> {
                    int x = stack.pop();
                    stack.push(stack.pop() * x);
                }
                case "/" -> {
                    int x = stack.pop();
                    stack.push(stack.pop() / x);
                }
                default -> stack.push(Integer.valueOf(token));
            }
        }
        return stack.pop();
    }
}
